package com.zx.framework.web.controller;

import java.util.Date;
import java.util.Locale;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import org.apache.log4j.Logger;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.WebApplicationContext;

import com.zx.framework.core.env.IMenuPosition;
import com.zx.framework.core.exception.ExceptionCode;
import com.zx.framework.core.util.ClientMap;
import com.zx.framework.web.exception.ValidateException;
import com.zx.framework.web.property.ManyCustomDateEditor;

/**
 * 所有controller的基类，提供了部分对于request，sesion，response的操作方法，日期绑定,分页等功能
 * @author stylewolf
 *
 */
public class BaseController  implements IMenuPosition,ExceptionCode{
	
	private static final Logger LOGGER = Logger.getLogger(BaseController.class);
	@Resource
	protected WebApplicationContext context;
	@Resource
	protected HttpServletRequest request;
	@Resource
	protected HttpServletResponse response;
	
	protected final static int SUCCESS = 1;
	
	protected final static int FAILED = 0;
	
	protected final static String SUCCESSSTR = "1";
	
	protected final static String FAILEDSTR = "0";
	
	/**
	 * 项目上下文
	 */
	public static final String BASE_PATH = "basePath";
	
	/**
	 * 菜单parameter的name
	 */
	protected final static String MODULEIDKEY = "moduleId";
	/**
	 * 渲染页面时，登录用户的信息key
	 */
	protected final static String LOGINKEY = "login";
	
	protected final static String SORTKEY = "sort";
	
	/**
	 * 所有响应中的通用性在此处理
	 * @param model
	 */
    @ModelAttribute  
    public void populateModel(Model model) {
    	if(LOGGER.isDebugEnabled()){
    		LOGGER.debug("init controller public property!");
    	}
    	model.addAttribute("now",new Date());
    	model.addAttribute(BASE_PATH,getBasePath());
    	//将当前登录用户添加至渲染model中
    	model.addAttribute(LOGINKEY, getSessionObject(SESSION_KEY));
    }  

	/**
	 * 获取i18n信息
	 * @param key
	 * @param args
	 * @return
	 */
	protected String getMessage(String key,String ... args ){
		return context.getMessage(key, args,"", Locale.getDefault());
	}
	
	/**
	 * 处理日期（yyyy-MM-dd HH:mm:ss）（ yyyy-MM-dd）（ HH:mm:ss）
	 * @param binder
	 * @throws Exception
	 */
	@InitBinder
    public void dateBinder(WebDataBinder binder) throws Exception {
		ManyCustomDateEditor customDateEditor = new ManyCustomDateEditor(true);
		binder.registerCustomEditor(Date.class, customDateEditor);
    }
	
	/**
	 * 获取项目的上下文路径
	 * @return
	 */
	protected String getBasePath(){
		return request.getContextPath()+"/";
	}
	
	/**
	 * 根据key获取session中的对象
	 * 
	 * @param <T>
	 * @param key
	 * @param type
	 * @return
	 */
	protected <T> T getSessionObject(String key, Class<T> type) {
		HttpSession session = request.getSession();
		if (session == null) {
			return null;
		} else {
			Object rs = session.getAttribute(key);
			if (rs == null) {
				return null;
			} else {
				return type.cast(rs);
			}
		}
	}
	
	/**
	 * 获取sessionKey的对应对象
	 * @param type
	 * @return
	 */
	protected <T> T getSessionKeyObject(Class<T> type)
	{
		return getSessionObject(SESSION_KEY, type);
	}
	/**
	 * session失效
	 */
	protected void sessionInvalidate(){
		HttpSession session = request.getSession();
		session.invalidate();
	}
	/**
	 * 获取authensessionKey的对应对象
	 * @param type
	 * @return
	 */
	protected <T> T getAuthenSessionKeyObject(Class<T> type)
	{
		return getSessionObject(AUTHEN_SESSION_KEY, type);
	}
	/**
	 * 保存session对象
	 * 
	 * @param key
	 * @param value
	 */
	protected void setSessionObject(String key, Object value) {
		HttpSession session = request.getSession();
		if (session == null) {
			return;
		} else {
			session.setAttribute(key, value);
		}
	}
	/**
	 * 获取session中的对象
	 * @param key
	 * @return
	 */
	protected Object getSessionObject(String key){
		HttpSession session = request.getSession();
		if (session == null) {
			return null;
		} else {
			return session.getAttribute(key);
		}
	}
	/**
	 * 设置httpstatus及消息
	 * @param status
	 * @param message
	 * @return
	 */
	protected String httpStatus(int status,String message){
		response.setStatus(status);
		return message;
	}
	/**
	 * 重新定义链式操作
	 * @return
	 */
	protected ClientMap clientMap(){
		return new ClientMap();
	}
	/**
	 * 利用jsr303进行校验数据，如果有未校验通过，则抛出异常
	 * @param t
	 */
	protected <T> void validate(T t){
		 ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); 
    	 Validator validator = factory.getValidator(); 
    	 Set<ConstraintViolation<T>> violations = validator.validate(t);
    	 if(violations.size() != 0) {
    		for (ConstraintViolation<T> constraintViolation : violations) {
    			throw new ValidateException(constraintViolation.getMessage());
			}
    	 }
	}
}
